package mergefilesrecursively;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class Demo {
    public static void main(String[] args)throws Exception {
        FileOutputStream fos = new FileOutputStream("day22-IO-01/merged_file.txt");

        File file = new File("day22-IO-01/Demo");

        mergeFilesRecursively(file, fos);

        fos.close();

    }

    public static void mergeFilesRecursively(File directory, FileOutputStream fos) throws Exception {
        if (directory.isDirectory()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        mergeFilesRecursively(file, fos);
                    }else {
                        FileInputStream fis = new FileInputStream(file);
                        byte[] bytes = new byte[4096];

                        int b;
                        while ((b = fis.read(bytes)) != -1) {
                            fos.write(bytes, 0, b);
                        }

                        fis.close();
                    }
                }
            }
        }
    }
}
